<?php

namespace LaiHe\LaravelHelper\Events\Subscribers;

use Monolog\Logger;
use Illuminate\Log\Writer;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Events\QueryExecuted;

class DBSubscriber
{
	/**
	 * @var Writer
	 */
	protected static $logger;

	/**
	 * 记录查询日志
	 *
	 * @param QueryExecuted $executed
	 */
	public function onQueryExecuted(QueryExecuted $executed)
	{
		static::getLogger()->info("$executed->time:$executed->sql", $executed->bindings);
	}

	/**
	 * 订阅数据库相关事件
	 *
	 * @param Dispatcher $events
	 */
	public function subscribe(Dispatcher $events)
	{
		$events->listen(QueryExecuted::class, 'Dt\LaravelHelper\Events\Subscribers\DBSubscriber@onQueryExecuted');
	}

	/**
	 * @return Writer
	 */
	protected static function getLogger()
	{
		if(!static::$logger){
			static::$logger = new Writer(new Logger(App::environment()), App::make('events'));
			static::$logger->useDailyFiles(storage_path('logs/sql.log'), config('app.log_max_files'), 'info');
		}

		return static::$logger;
	}
}
